﻿using System;
using System.Management;

namespace Vicos.Management
{
    class Counters
    {
        public static int getVMCount(String computer)
        {
            int result;
            try
            {
                ObjectQuery vm_q = new ObjectQuery("SELECT * FROM msvm_computersystem WHERE Caption='Virtual Machine' AND EnabledState=2");
                ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\virtualization", computer));
                scope.Connect();

                ManagementObjectSearcher searcher =
                            new ManagementObjectSearcher(scope, vm_q);
                result = searcher.Get().Count;
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                result = -1;
            }

            return result;
        }



        public static double getProcessorRatio(String computer)
        {
            int vmproc_count, proc_count = 0;
            double ratio;

            try
            {
                // get the number of virtual processors
                ObjectQuery vmproc_q = new ObjectQuery("SELECT * FROM MSVM_Processor");
                ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\root\\virtualization", computer));
                scope.Connect();

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, vmproc_q);
                vmproc_count = searcher.Get().Count;

                // get the number of logical processors avaliable on the computer processor
                ObjectQuery proc_q = new ObjectQuery("SELECT * FROM Win32_Processor");
                ManagementScope scope2 = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", computer));
                scope2.Connect();

                ManagementObjectSearcher searcher2 =
                    new ManagementObjectSearcher(scope2, proc_q);

                foreach (ManagementObject proc in searcher2.Get())
                {
                    proc_count += Int32.Parse(proc["NumberOfLogicalProcessors"].ToString());
                }

                ratio = ((double)vmproc_count) / proc_count;

            }
            catch (System.Runtime.InteropServices.COMException)
            {
                ratio = -1;
            }

            return ratio;
        }
    }
}
